﻿using System.Net.WebSockets;
using System.Text;

namespace WebApi.Controllers
{
    public class WebSocketHandler
    {
        private WebSocket webSocket;
        private WebSocketConnectionManager connectionManager;
        public WebSocketHandler(WebSocketConnectionManager connectionManager)
        {
            this.connectionManager = connectionManager;
        }

        public async Task HandleWebSocketAsync(WebSocket socket)
        {
            this.webSocket = socket;
            this.connectionManager.AddWebSocket(webSocket);
            // 连接成功后，增加在线用户数量
            connectionManager.IncrementOnlineUserCount();

            try
            {
                byte[] buffer = new byte[1024];
                WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                while (!result.CloseStatus.HasValue)
                {
                    string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                    Console.WriteLine($"Received: {message}");

                    // Process and respond to the message here

                    await socket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

                    result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                }

                if (result.CloseStatus.HasValue)
                {
                    CloseWebSocket();
                    await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    // 指定要写入的文件路径

                    string executablePath = System.Reflection.Assembly.GetEntryAssembly().Location;
                    string executableDirectory = Path.GetDirectoryName(executablePath);
                    string fileName = "error.log"; // 文件名
                    string filePath = Path.Combine(executableDirectory, fileName);
                    if (!File.Exists(filePath))
                    {
                        using (File.Create(filePath))
                        {
                            // 文件流在这个块内创建并打开，随后会在块结束时自动关闭。
                        }
                    }

                    // 使用 StreamWriter 打开文件以追加方式写入错误信息
                    using (StreamWriter writer = File.AppendText(filePath))
                    {
                        // 写入错误信息和时间戳
                        writer.WriteLine($"[{DateTime.Now}] {ex.Message}");
                    }
                }
                catch (Exception)
                {
                    // 处理可能的文件操作异常
                    Console.WriteLine("写入错误日志时发生异常：" + ex.Message);
                }


                CloseWebSocket();
            }

        }
        private void CloseWebSocket()
        {
            if (this.webSocket != null)
            {
                this.connectionManager.RemoveWebSocket(this.webSocket);

                // 断开连接后，减少在线用户数量
                connectionManager.DecrementOnlineUserCount();

                this.webSocket.Dispose();
            }


        }
    }
}
